package com.ebelter.btlibrary.btble.ble;

import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;

import com.ebelter.btlibrary.btble.ble.bluetooth.callback.BleSatusCallback;
import com.ebelter.btlibrary.btble.ble.bluetooth.callback.ConnectCallback;
import com.ebelter.btlibrary.btble.ble.bluetooth.callback.ScanResultCallback;
import com.ebelter.btlibrary.btble.ble.bluetooth.device.BlueToothServer;
import com.ebelter.btlibrary.btble.ble.bluetooth.device.OnDeviceBindFoundListener;
import com.ebelter.btlibrary.btble.common.Fields;
import com.ebelter.btlibrary.util.SpUtil;
import com.ebelter.btlibrary.util.ULog;


/**
 * @author 作 者：pan
 * @filename 文件名：BleManager.java
 * @description 描 述：蓝牙管理器
 * @date 时 间：2017-11-3
 * @Copyright 版 权：倍泰源代码，版权归深圳市倍泰健康测量分析技术有限公司所有。
 */
public abstract class BleManager {

    private static final String TAG = "BleManager";
    protected static int REQUEST_ENABLE_BT = 101;

    //    protected static BleManager instance;
    protected static BlueToothServer mBlueToothServer;
    protected static Activity mActivity;
    protected BluetoothDevice curDevice;
    public ScanResultCallback mScanResultCallback;
    protected static ConnectCallback customConnectCallback;
    public ConnectStatus mConnectStatus = ConnectStatus.DISCONNECTED;
    private boolean isDisconnectOnScreenOff = true;


    public void init(Activity aty) {
        mActivity = aty;
        initBleService(aty);
        setBleParams();
    }

    protected abstract void initBleService(Activity aty);

    protected abstract void setBleParams();

    public boolean isDisconnectOnScreenOff() {
        return this.isDisconnectOnScreenOff;
    }

    public void setDisconnetOnScreenOff(boolean disconnectOnScreenOff) {
        this.isDisconnectOnScreenOff = disconnectOnScreenOff;
    }

    /**
     * 2. 打开蓝牙
     */
    public static void open(Activity aty) {

        if (aty == null) {
            return;
        }
        // Initializes Bluetooth adapter.
        final BluetoothManager bluetoothManager = (BluetoothManager) aty.getSystemService(Context.BLUETOOTH_SERVICE);
        BluetoothAdapter mBluetoothAdapter = null;
        if (bluetoothManager != null) {
            mBluetoothAdapter = bluetoothManager.getAdapter();
        }



        ULog.i(TAG, "---open---mBluetoothAdapter = " + mBluetoothAdapter);
        // Ensures Bluetooth is available on the device and it is enabled. If not,
        // displays a dialog requesting user permission to enable Bluetooth.
        if (mBluetoothAdapter != null && !mBluetoothAdapter.isEnabled()) {
            Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            aty.startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
        }
        if (mBluetoothAdapter != null) {
            ULog.i(TAG, "---open---isEnabled = " + mBluetoothAdapter.isEnabled());
        }
    }


    /**
     * 注册BleSatusCallback 手机蓝牙状态改变监听回调
     */
    public void registerBleSatusCallback(BleSatusCallback callback) {
        if (mBlueToothServer != null) {
            mBlueToothServer.setBleSatusCallback(callback);
        }
    }

    public void registerConnectCallback(ConnectCallback callback) {
        this.customConnectCallback = callback;
    }

    public void unregisterConnectCallback() {
        this.customConnectCallback = null;
    }

    /**
     * 3. 扫描设备
     */
    public void startScan(ScanResultCallback callback) {
        if (mBlueToothServer != null) {
            this.mScanResultCallback = callback;
            mBlueToothServer.startScanDevice();
        }else {
            ULog.i(TAG,"--BleManger--startScan--扫描失败");
        }
    }

    public boolean isScaning() {
        return mBlueToothServer != null && mBlueToothServer.mScanning;
    }

    public void startScan() {
        if (mBlueToothServer != null) {
            mBlueToothServer.startScanDevice();
        }
    }

    /**
     * 4. 绑定设备
     */
    public void startConnect(BluetoothDevice device) {
        if (mBlueToothServer != null) {
            mBlueToothServer.startConnectDevice(device);
        }
    }

    public void startConnect(String deviceAddress) {
        if (mBlueToothServer != null) {
            mBlueToothServer.startConnectDevice(deviceAddress);
        }
    }

    /**
     * 5. 解绑设备
     */
    public void unbindDevice() {
        if (mBlueToothServer != null) {
            mBlueToothServer.unbindDevice();
        }
    }

    /**
     * 6. 断开连接
     */
    public void disConnectDevice() {
        if (mBlueToothServer != null) {
            mBlueToothServer.disConnectAndStopScan();
        }
    }

    private void resConnectDevice() {
        if (mBlueToothServer != null) {
            mBlueToothServer.reConnect();
        }
    }

    /**
     * 是否已绑定体脂秤
     */
    public boolean isDeviceBound() {
        //读取绑定的设备的mac
//        SharePrefrenceHelper spf = new SharePrefrenceHelper(mActivity.getApplicationContext());
//        spf.open(FileNames.STRING_FILE);
//        String mac = spf.getString(Fields.DEVICE_MAC);
//        OnDeviceBindFoundListener.mac = mac;
        OnDeviceBindFoundListener.mac = SpUtil.readString(Fields.DEVICE_MAC,null);
        return OnDeviceBindFoundListener.mac != null;
    }


    /**
     * 是否已连接
     */
    public boolean isConnected() {
        return mConnectStatus == ConnectStatus.CONNECTED;
    }


    /**
     * 注册息屏监听广播
     */
    public void registSreenStatusReceiver() {
        IntentFilter screenStatusIF = new IntentFilter();
        screenStatusIF.addAction(Intent.ACTION_SCREEN_ON);
        screenStatusIF.addAction(Intent.ACTION_SCREEN_OFF);
        mActivity.registerReceiver(mScreenStatusReceiver, screenStatusIF);
    }


    protected ScanResultCallback scanResultCallback = new ScanResultCallback() {

        @Override
        public void onDiscovered(BluetoothDevice device) {
            ULog.i(TAG, "-----onDiscovered------name = " + device.getName() + ", Addr = " + device.getAddress());
//            if (isDeviceBound()&& OnDeviceBindFoundListener.mac.equals(device.getAddress())) {  //zcq删于201804031745
//                startConnect(device);
//            }
            if (mScanResultCallback != null) {
                mScanResultCallback.onDiscovered(device);
            }
        }

    };


    public enum ConnectStatus {

        /**
         * 已连接
         */
        CONNECTED,

        /**
         * 正在连接
         */
        CONNECTING,

        /**
         * 已断开
         */
        DISCONNECTED;
    }


    /**
     * 监听息屏广播
     */
    BroadcastReceiver mScreenStatusReceiver = new BroadcastReceiver() {
        String SCREEN_ON = "android.intent.action.SCREEN_ON";
        String SCREEN_OFF = "android.intent.action.SCREEN_OFF";

        @Override
        public void onReceive(Context context, Intent intent) {
            if (SCREEN_ON.equals(intent.getAction())) {
                ULog.i(TAG, "-----SCREEN_ON-----startConnect");
                if (mConnectStatus == ConnectStatus.DISCONNECTED) {
                   // startScan();
                   // resConnectDevice();//曾彩青改
            }

            } else if (SCREEN_OFF.equals(intent.getAction())) {
                if (isDisconnectOnScreenOff) {
                    disConnectDevice();
                }
                ULog.i(TAG, "-----SCREEN_OFF-----disConnectDevice");
            }
        }
    };


    /**
     * 在Activity的Destroy方法中必须调用此方法，否则可能导致内存泄露
     * <p>
     * 释放蓝牙模块资源的方法
     */
    public void release() {
        //注销广播
        if (mActivity != null) {
            mActivity.unregisterReceiver(mScreenStatusReceiver);
            mActivity = null;
        }


        //断开连接
        disConnectDevice();

        mScanResultCallback = null;

        //释放其他资源
//        mWeightMessage.release();
//        weightDataHandler.release();
        mBlueToothServer.release();
        mBlueToothServer = null;

    }


}
